package roguespace;

import java.io.File;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import jgame.Highscore;
import jgame.JGFont;
import jgame.JGPoint;
import jgame.platform.StdGame;
import treeship.core.exceptions.CantDoThatException;
import treeship.core.service.Nexus;
import treeship.core.service.impl.DimensionalFactory1D;
import treeship.core.ship.impl.TreeShip;

/** Minimal shooter illustrating Eclipse usage. */
public class TheGame3 extends StdGame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public static void main(String[] args) {
		// new TheGame2(parseSizeArgs(args, 0));
		new TheGame3(new JGPoint(640, 480));
	}

	public TheGame3() {
		initEngineApplet();
	}

	public TheGame3(JGPoint size) {
		initEngine(size.x, size.y);
	}

	JGFont scoring_font = new JGFont("Arial", 0, 8);
	private LinkedList<TreeShip> enemies = new LinkedList<TreeShip>();

	@Override
	public void initCanvas() {
		setCanvasSettings(32, 24, 8, 8, null, null, null);
	}

	@Override
	public void initGame() {
		defineMedia("mygame.tbl");
		if (isMidlet()) {
			setFrameRate(20, 1);
			setGameSpeed(2.0);
		} else {
			setFrameRate(45, 1);
		}
		setHighscores(10, new Highscore(0, "nobody"), 15);
		startgame_ingame = true;
		String hierarchyPath = "thegame2.xml";
		File file = new File(hierarchyPath);
		Nexus.startup(file, true, new DimensionalFactory1D());
	}

	@Override
	public void initNewLife() {
		removeObjects(null, 0);
		new TPlayer(this, pfWidth() / 2, pfHeight() - 32, 5);
	}

	@Override
	public void startGameOver() {
		removeObjects(null, 0);
		fillWithEnemies(enemies, level);
	}

	public void doFrameInGame() {
		moveObjects();
		checkCollision(2, 1); // enemies hit player
		checkCollision(4, 2); // bullets hit enemies
		// checkCollision(2, 2); // enemies vs enemies
		if (!enemies.isEmpty()) {
			TreeShip remove = enemies.removeFirst();
			new TEnemy(this, remove);
		}
		if (enemies.isEmpty() && countObjects("enemy", 0) == 0) {
			levelDone();
		}
	}

	@Override
	public void incrementLevel() {
		score += 50;
		if (level < 7) {
			level++;
		}
		stage++;

		fillWithEnemies(enemies, level);
	}

	private void fillWithEnemies(LinkedList<TreeShip> li, int diff) {
		li.clear();
		try {
			Map<String, Double> map = new HashMap<String, Double>();
			map.put("danger", new Double(1000 * diff + 1));
			TreeShip ship = Nexus.getFactory().buildShip("Universe", null, map);
			li.addAll(ship.getChildren());
		} catch (CantDoThatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
